package com.mimc.framework.interceptors;

import cn.hutool.core.util.StrUtil;
import com.mimc.common.exception.ServiceException;
import com.mimc.framework.domain.AjaxResult;
import com.mimc.framework.domain.R;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.core.JFinal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;

public class ExceptionInterceptor implements Interceptor {
    private static final Logger log = LoggerFactory.getLogger(ExceptionInterceptor.class);


    @Override
    public void intercept(Invocation inv) {
        Controller controller = inv.getController();
        HttpServletRequest request = controller.getRequest();
        try {
            inv.invoke();
        } catch (Exception e) {
            //输入到日记文件
            doLog(inv, e);
            if(e instanceof ServiceException){
                AjaxResult ajaxResult=this.handleApiServiceException((ServiceException) e);
                controller.renderJson(ajaxResult);
            }else{
                inv.invoke();
            }
        }
    }

    private void doLog(Invocation ai,Exception e) {
        //开发模式
        if(JFinal.me().getConstants().getDevMode()){
            e.printStackTrace();
        }
        //业务异常不记录
        //if( e instanceof NormalException) return;
        StringBuilder sb =new StringBuilder("\n---全局异常处理拦截---\n");
        sb.append("Controller:").append(ai.getController().getClass().getName()).append("\n");
        sb.append("Method:").append(ai.getMethodName()).append("\n");
        sb.append("Exception Type:").append(e.getClass().getName()).append("\n");
        sb.append("Exception Details:");
        log.error(sb.toString(), e);
    }
    public AjaxResult handleApiServiceException(ServiceException e)
    {
        log.error(e.getMessage());
        Integer code = e.getCode();
        String tansCode = e.getTansCode();
        if(StrUtil.isBlankIfStr(code)){
            code= R.FAIL;
        }
        return AjaxResult.error(code, e.getMessage(),tansCode);
    }
}
